package FIT::Document::Handler::ExpectedError;

use FIT::Class;
use FIT::Util::SpecialChars;
use FIT::Document::Transformer;

extends 'FIT::Document::Handler::Base';

sub handle {
    my ($fixture, $cell, @handlers) = @_;
    my $marked = $cell->detect_mark($MARKER_EXPECTED_ERROR);

    unless ($marked) {
        $self->run_next_handler($fixture, $cell, @handlers);
        return;
    }

    my $context = $fixture->context;
    my ($error, $error_count);

    $context->run_silently(sub {

        # errors can be in the handler chain, in which case $@ will not be empty
        # or they could have been gobbled up by some inner eval, in which case $@ will
        # be empty, but the Error tally will rise, unless it was all run_silently(),
        # like we are going to be

        $cell->clear_mark($MARKER_EXPECTED_ERROR);
        my $initial_error_count = $context->error;

        eval { $self->run_next_handler($fixture, $cell, @handlers) };

        $error = $@;
        $error_count = $context->error - $initial_error_count;

        die "Error count has decreased [$initial_error_count, $error]" if $error_count < 0;

        $cell->insert_mark($MARKER_EXPECTED_ERROR);

    });

    transform { ($error || $error_count)? Right: Wrong } $cell;
}


=head1 NAME

FIT::Document::Handler::ExpectedError - expect an error and FAIL if there was none


=head1 DESCRIPTION

This handler lets you to add an expectation for a cell to produce an error. If
there was one, the cell will be marked Right. Otherwise it will be marked Wrong.

=cut

